/**
 * @description 获取地址栏参数
 * @param {string} key 参数名
 * @return {string} 参数值
 **/
export const queryParams = key => {
	if (!key) return null;
	const url = new URL(location.href);
	const value = url.searchParams.get(key);
	return value;
};

/**
 * @description 检测重复数据
 * @param {Array} arrary 数组
 * @param {String} key 键
 * @return {Boolean} 是否重复
 **/
export const hasRepeat = (data, key) => {
	const seen = new Set();
	return data.some(item => {
		const value = item[key];
		if (seen.has(value)) return true;
		seen.add(value);
		return false;
	});
};

/**
 * @description 从 start 开始查找下一个可用编号
 * @param {number[]} numbers 现有编号数组（无重复，但可能无序）
 * @param {number} [start=1] 起始查询位置
 * @return {number} 下一个可用的最小编号（>= start）
 */
export const getNextNumber = (numbers, start = 1) => {
	const occupied = new Set(numbers);
	let candidate = start;
	while (occupied.has(candidate)) {
		candidate++;
	}
	return candidate;
};

/**
 * @description 路由文件路径拼接
 * @param {String} path: 文件夹
 * @return {Function}
 */
export const routePath = path => {
	return () => import(`@/views/${path}/index.vue`);
};

/**
 * @description 表单验证公用方法
 * @param {Object} formRef - Element UI 表单的 ref 引用
 * @return {Promise<boolean>} - true 验证通过，false 验证失败
 */
export const validateForm = formRef => {
	return new Promise(resolve => {
		formRef ? formRef.validate(valid => resolve(valid)) : resolve(false);
	});
};

/**
 * @description 路由菜单过滤（支持多层级嵌套）
 * @param {Array} routes - 路由数组
 * @param {Boolean} isLoop - 是否循环过滤
 * @return {Array} - 过滤后的路由数组
 **/
export const filterRoutes = (routes, isLoop = true) => {
	return routes.filter(route => {
		if (Object.hasOwn(route, "hidden") && route.hidden === true) return false;
		if (isLoop && Object.hasOwn(route, "children") && Array.isArray(route.children)) {
			route.children = filterRoutes(route.children, isLoop);
		}
		return true;
	});
};
